package com.zzz.demo.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class UpdateListGenerator {

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(UpdateListGenerator.class);
    private String text = ""; // 剪贴板中的内容

    /**
     * 从配置文件中获取数据
     */
    public JSONArray getProjectRegextByName(String filePath, String projectName) {
        File configFile = new File(filePath);
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(configFile, "UTF-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
        return jsonObject.getJSONArray(projectName);
    }

    /***
     * 获取剪贴板内容
     */
    public String getSysClipboardText() {
        String text = "";
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪切板中的内容
        Transferable clipTf = sysClip.getContents(null);
        if (clipTf != null) {
            // 检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    text = (String) clipTf.getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return text;
    }

    /**
     * 处理从剪贴板获取的内容 写入到文件
     */
    public StringBuffer writeList2File(String projectName) {
        StringBuffer buffer = new StringBuffer();
        String configPath = Thread.currentThread().getContextClassLoader().getResource("config/yunchuang").getPath();
        // 先判断一下剪贴板中有没有内容
        if (text == null || "".equals(text)) {
            logger.warn("请先复制更新文件列表!");
            return buffer;
        }
        // 获取要替换的字符
        JSONArray jsonArray = getProjectRegextByName(configPath, projectName);
        StringReader stringReader = new StringReader(text);
        BufferedReader bufferedReader = new BufferedReader(stringReader);
        String str;
        try {
            /**
             * 创建输入文件
             */
            String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            File output = new File(classPath + "output");
            File listFile = new File(classPath + "output/list.txt");
            if (!output.exists()) {
                // 新建文件夹
                output.mkdirs();
            }
            // 如果文件已存在则删掉
            if (listFile.exists()) {
                // 这个文件被占用时删除不掉
                // 但是仍然返回true
                listFile.getAbsoluteFile().delete();
                listFile.createNewFile();
            }
            /**
             * 把文件列表写入到输出文件
             */
            FileOutputStream fileOutputStream = new FileOutputStream(listFile, false);
            Set<String> fileList = new HashSet<String>();
            while ((str = bufferedReader.readLine()) != null) {
                // 去重复文件
                if (!fileList.contains(str)) {
                    if (!"".equals(str.trim())) {
                        fileList.add(str);
                        String tempStr = str;
                        for (Object regStr : jsonArray) {
                            tempStr = tempStr.replace((String) regStr, "").trim();
                        }
                        // 处理模块名称
                        String moduleName = StringUtils.substringBefore(tempStr, "/");
                        // 去掉模块名之后
                        tempStr = StringUtils.removeStart(tempStr, moduleName + "/");
                        // src下的java文件
                        if (tempStr.startsWith("src")) {
                            // 针对maven项目，test下面的不处理
                            String javaFile = tempStr.replace("src/main/", "");
                            String suffix = javaFile.substring(javaFile.indexOf(".") + 1);
                            // 需要编译的
                            javaFile = javaFile.substring(javaFile.indexOf("/"));
                            if (suffix.equalsIgnoreCase("java")) {
                                tempStr = moduleName + "/WEB-INF/classes"
                                        + javaFile.substring(0, javaFile.indexOf(".") + 1) + "class";
                            } else if (suffix.equalsIgnoreCase("xml")) {
                                tempStr = moduleName + "/WEB-INF/classes"
                                        + javaFile.substring(0, javaFile.indexOf(".") + 1) + "xml";
                            } else {
                                // 不需要编译的
                                tempStr = moduleName + javaFile;
                            }
                        } else {
                            logger.error("剪贴板的内容不是更新文件列表或者项目名不对!");
                            return buffer;
                        }
                        fileOutputStream.write((tempStr + "\n").getBytes());
                        buffer.append(tempStr + "\n");
                    }
                }
            }
            fileList.clear();
            fileOutputStream.close();
            logger.info("更新文件列表生成成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(buffer);
        return buffer;
    }


    public UpdateListGenerator() {
    }

    public String getFilePath(String projectName,String content) {
        if (StringUtils.isEmpty(content)) {
            text = getSysClipboardText();
        } else {
            text = content;
        }
       return writeList2File(projectName).toString();
    }

    public static void main(String[] args) {
        new UpdateListGenerator().getFilePath("yunling",null);
    }
}
